package top.xchch.tool.cipher.atguigu;

public class KaiserDemo {
    public static void main(String[] args) {
        String input = "Hello World";
        // 把原文右移三位
        int key = 3;
        String output = encryptKaiser(input, key);
        System.out.println("密文: " + output); // 密文: Khoor#Zruog

        String src= decryptKaiser(output, key);
        System.out.println("原文: " + src); // 原文: Hello World


    }

    /**
     * 凯撒加密
     */
    private static String encryptKaiser(String s, int key) {
        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char ch : chars) {
            int b = ch;
            // 右移
            b += key;
            char newB = (char) b;
            sb.append(newB);
        }
        return sb.toString();
    }

    /**
     * 凯撒解密
     */
    private static String decryptKaiser(String s, int key) {
        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char ch : chars) {
            int b = ch;
            // 右移
            b -= key;
            char newB = (char) b;
            sb.append(newB);
        }
        return sb.toString();
    }
}
